import * as turf from '@turf/turf'
import { httpRequest } from '@/api/httpRequest'
import _ from 'lodash'
import { useEarthStore } from "@/stores/earth";

function imgsearch(params) {
  const earthStore = useEarthStore();

    function getNumberOfXTilesAtLevel(level) {
        return 2 << level
    }
    function getNumberOfYTilesAtLevel(level) {
        return 1 << level
    }

    function tileXYToNativeRectangle(x, y, level, result) {
        const rectangleRadians = tileXYToRectangle(x, y, level, result)
        rectangleRadians.west = Cesium.Math.toDegrees(rectangleRadians.west)
        rectangleRadians.south = Cesium.Math.toDegrees(rectangleRadians.south)
        rectangleRadians.east = Cesium.Math.toDegrees(rectangleRadians.east)
        rectangleRadians.north = Cesium.Math.toDegrees(rectangleRadians.north)
        return rectangleRadians
    }

    function tileXYToRectangle(x, y, level, result) {
        const rectangle = Cesium.Rectangle.MAX_VALUE

        const xTiles = getNumberOfXTilesAtLevel(level)
        const yTiles = getNumberOfYTilesAtLevel(level)

        const xTileWidth = rectangle.width / xTiles
        const west = x * xTileWidth + rectangle.west
        const east = (x + 1) * xTileWidth + rectangle.west

        const yTileHeight = rectangle.height / yTiles
        const north = rectangle.north - y * yTileHeight
        const south = rectangle.north - (y + 1) * yTileHeight
        console.log(north);

        if (!Cesium.defined(result)) {
            result = new Rectangle(west, south, east, north)
        }

        result.west = west
        result.south = south
        result.east = east
        result.north = north
        return result
    }

    function positionToTileXY(position, level, result) {
        const rectangle = Cesium.Rectangle.MAX_VALUE
        if (!Cesium.Rectangle.contains(rectangle, position)) {
            // outside the bounds of the tiling scheme
            return undefined
        }

        const xTiles = getNumberOfXTilesAtLevel(level)
        const yTiles = getNumberOfYTilesAtLevel(level)

        const xTileWidth = rectangle.width / xTiles
        const yTileHeight = rectangle.height / yTiles

        let longitude = position.longitude
        if (rectangle.east < rectangle.west) {
            longitude += CesiumMath.TWO_PI
        }

        let xTileCoordinate = ((longitude - rectangle.west) / xTileWidth) | 0
        if (xTileCoordinate >= xTiles) {
            xTileCoordinate = xTiles - 1
        }

        let yTileCoordinate =
            ((rectangle.north - position.latitude) / yTileHeight) | 0
        if (yTileCoordinate >= yTiles) {
            yTileCoordinate = yTiles - 1
        }

        if (!Cesium.defined(result)) {
            return new Cartesian2(xTileCoordinate, yTileCoordinate)
        }

        result.x = xTileCoordinate
        result.y = yTileCoordinate
        return result
    }

    function pointclick(item) {
      let prename = item.id.split("_")[0];
    
      let filename = "";
    
      if (_.has(item.properties, "name")) {
        filename = item.properties["name"];
      }
      if (_.has(item.properties, "filename")) {
        filename = item.properties["filename"];
      }
    
      earthStore.panoramaurl = "/juhetuceng/" + prename + "10m/" + filename;
      earthStore.showPanorama = true;
    }

    function getImgFeature(event) {
        var ray = viewer.camera.getPickRay(event.position)
        let scene = viewer.scene

        const pickedPosition = scene.globe.pick(ray, scene)
        if (!Cesium.defined(pickedPosition)) {
            return
        }

        // 从wmts获取pick结果（------）
        const pickedLocation =
            scene.globe.ellipsoid.cartesianToCartographic(pickedPosition)
        const tilesToRender = scene.globe._surface._tilesToRender
        let pickedTile
        for (
            let textureIndex = 0;
            !Cesium.defined(pickedTile) && textureIndex < tilesToRender.length;
            ++textureIndex
        ) {
            const tile = tilesToRender[textureIndex]
            if (Cesium.Rectangle.contains(tile.rectangle, pickedLocation)) {
                pickedTile = tile
            }
        }

        let result = new Cesium.Rectangle()
        let result1 = new Cesium.Cartesian2()
        const longitudeLatitudeProjectedScratch = new Cesium.Cartesian3()
        longitudeLatitudeProjectedScratch.x = Cesium.Math.toDegrees(
            pickedLocation.longitude,
        )
        longitudeLatitudeProjectedScratch.y = Cesium.Math.toDegrees(
            pickedLocation.latitude,
        )
        const projected = longitudeLatitudeProjectedScratch
        const rectangle = tileXYToNativeRectangle(
            pickedTile.x,
            pickedTile.y,
            pickedTile.level,
            result,
        )
        let x = ((256 * (projected.x - rectangle.west)) / rectangle.width) | 0
        let y = ((256 * (rectangle.north - projected.y)) / rectangle.height) | 0
        httpRequest
        .get(
          `/jiejing/geoserver/test_tif/wms?service=WMS&version=1.1.1&request=GetFeatureInfo&layers=juhetuceng&width=256&height=256&srs=EPSG%3A4326&query_layers=juhetuceng&info_format=application%2Fjson&x=${x}&y=${y}&bbox=${rectangle.west},${rectangle.south},${rectangle.east},${rectangle.north}`
        )
        .then((res) => {

          if (res.features.length != 0) {
            pointclick(res.features[0])
          }else{
            
            httpRequest
            .get(
              `/jiejing/geoserver/test_tif/wms?service=WMS&version=1.1.1&request=GetFeatureInfo&layers=jiejing&width=256&height=256&srs=EPSG%3A4326&query_layers=jiejing&info_format=application%2Fjson&x=${x}&y=${y}&bbox=${rectangle.west},${rectangle.south},${rectangle.east},${rectangle.north}`
            )
            .then((res1) => {
              if (res1.features.length != 0) {
                res1.features[0].id = 'zhengzhou_aaaa'
                console.log(res1.features[0]);
                pointclick(res1.features[0])
              }else{

              }
            })
          }
        })



    }

    function getImgFeature1(event) {
        var ray = viewer.camera.getPickRay(event.position)
        let scene = viewer.scene

        const pickedPosition = scene.globe.pick(ray, scene)
        if (!Cesium.defined(pickedPosition)) {
            return
        }

        const pickedLocation =
            scene.globe.ellipsoid.cartesianToCartographic(pickedPosition)

        const tilesToRender = scene.globe._surface._tilesToRender
        let pickedTile

        for (
            let textureIndex = 0;
            !Cesium.defined(pickedTile) && textureIndex < tilesToRender.length;
            ++textureIndex
        ) {
            const tile = tilesToRender[textureIndex]
            if (Cesium.Rectangle.contains(tile.rectangle, pickedLocation)) {
                pickedTile = tile
            }
        }

        let result = new Cesium.Rectangle()
        let result1 = new Cesium.Cartesian2()
        // tileXYToRectangle(pickedTile.x,pickedTile.y,pickedTile.level,result)

        // positionToTileXY(pickedLocation,pickedTile.level,result1)

        const rectangleScratch = new Cesium.Rectangle()

        const longitudeLatitudeProjectedScratch = new Cesium.Cartesian3()
        longitudeLatitudeProjectedScratch.x = Cesium.Math.toDegrees(
            pickedLocation.longitude,
        )
        longitudeLatitudeProjectedScratch.y = Cesium.Math.toDegrees(
            pickedLocation.latitude,
        )
        const projected = longitudeLatitudeProjectedScratch
        const rectangle = tileXYToNativeRectangle(
            pickedTile.x,
            pickedTile.y,
            pickedTile.level,
            result,
        )

        console.log(rectangle)
        let x = ((256 * (projected.x - rectangle.west)) / rectangle.width) | 0

        console.log(x)
        let y = ((256 * (rectangle.north - projected.y)) / rectangle.height) | 0
        console.log(y)

        // console.log(west,south,east,north);
        // console.log(west,south,east,north);
        console.log(result1)
        console.log(pickedTile)

        // provider.pickFeatures(
        //   imagery.x,
        //   imagery.y,
        //   imagery.level,
        //   pickedLocation.longitude,
        //   pickedLocation.latitude
        // )

        const promises = []
        const imageryLayers = []

        // console.log(viewer.imageryLayers)

        // pickImageryHelper(scene, pickedLocation, true, function (imagery) {
        //   const provider = imagery.imageryLayer.imageryProvider;
        //   const promise = provider.pickFeatures(
        //     imagery.x,
        //     imagery.y,
        //     imagery.level,
        //     pickedLocation.longitude,
        //     pickedLocation.latitude
        //   );
        //   if (defined(promise)) {
        //     promises.push(promise);
        //     imageryLayers.push(imagery.imageryLayer);
        //   }
        // });

        // var featuresPromise = viewer.imageryLayers.pickImageryLayerFeatures(
        //   pickRay,
        //   viewer.scene
        // );

        // let pos = getMouseInfo(event.position).wgs84Position

        // console.log(pos);

        // return

        // let posarr = path_arr.split("-")[0].split(",");
        // var point = turf.point([pos['lng'] * 1, pos['lat'] * 1]);
        // var buffered = turf.buffer(point, 5, { units: "meters", steps: 1 });
        // var bbox = turf.bbox(buffered);
        // httpRequest
        // .get(
        //   "/geoserver/test_tif/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=juhetuceng&maxFeatures=50&outputFormat=application%2Fjson&BBOX=" +
        //     bbox.join(",")
        // )
        // .then((res) => {
        //   console.log(res);
        // })
    }

    function getMouseInfo(position) {
        let scene = viewer.scene
        let target = scene.pick(position)
        let cartesian = undefined
        let surfaceCartesian = undefined
        let wgs84Position = undefined
        let wgs84SurfacePosition = undefined
        if (scene.pickPositionSupported) {
            cartesian = scene.pickPosition(position)
        }
        if (cartesian) {
            let c = Cesium.Ellipsoid.WGS84.cartesianToCartographic(cartesian)
            if (c) {
                wgs84Position = {
                    lng: Cesium.Math.toDegrees(c.longitude),
                    lat: Cesium.Math.toDegrees(c.latitude),
                    alt: c.height,
                }
            }
        }
        if (
            scene.mode === Cesium.SceneMode.SCENE3D &&
            !(viewer.terrainProvider instanceof Cesium.EllipsoidTerrainProvider)
        ) {
            let ray = scene.camera.getPickRay(position)
            surfaceCartesian = scene.globe.pick(ray, scene)
        } else {
            surfaceCartesian = scene.camera.pickEllipsoid(
                position,
                Cesium.Ellipsoid.WGS84,
            )
        }
        if (surfaceCartesian) {
            let c =
                Cesium.Ellipsoid.WGS84.cartesianToCartographic(surfaceCartesian)
            if (c) {
                wgs84SurfacePosition = {
                    lng: Cesium.Math.toDegrees(c.longitude),
                    lat: Cesium.Math.toDegrees(c.latitude),
                    alt: c.height,
                }
            }
        }

        return {
            target: target,
            windowPosition: position,
            position: cartesian,
            wgs84Position: wgs84Position,
            surfacePosition: surfaceCartesian,
            wgs84SurfacePosition: wgs84SurfacePosition,
        }
    }

    return { getImgFeature, getMouseInfo }
}

export default imgsearch
// export {getImgFeature, getMouseInfo}
